package com.laicunba.service.fuiou.impl;

import java.io.ByteArrayInputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.laicunba.constant.GloabConstant;
import com.laicunba.service.fuiou.FuiouOrderCreateService;
import com.laicunba.util.AssertUtil;
import com.laicunba.util.HttpUtil;
import com.laicunba.util.StringUtil;

@Service
public class FuiouOrderCreateServiceImpl implements FuiouOrderCreateService {
	private static final Logger LOG = Logger.getLogger(FuiouOrderCreateServiceImpl.class);
	private String prefix = GloabConstant.FUIOU_URL_PREFIX;
	private String mchntcd = GloabConstant.FUIOU_MCHNTCD;
	private String mchntKey = GloabConstant.FUIOU_MCHNT_KEY;

	@SuppressWarnings("unchecked")
	@Override
	public CreateOrderResult createOrder(CreateOrderParam param) {

		try {

			StringBuffer sb = new StringBuffer();
			sb.append("<FM>");
			sb.append("<MchntCd>").append(mchntcd).append("</MchntCd>");
			sb.append("<Amt>").append(param.getAmt()).append("</Amt>");
			sb.append("<Rmk1>").append(param.getRmk1()).append("</Rmk1>");
			sb.append("<Rmk2>").append(param.getRmk2()).append("</Rmk2>");
			sb.append("<Rmk3>").append(param.getRmk3()).append("</Rmk3>");
			// MchntCd + "|"+Amt+"|"+mchnt_key 做 md5 摘要
			String sign = StringUtil.md5(mchntcd + "|" + param.getAmt() + "|" + mchntKey);
			sb.append("<Sign>").append(sign).append("</Sign>");
			sb.append("</FM>");

			Map paremeter = new HashMap();
			paremeter.put("FM", sb.toString());

			String xmlResult = HttpUtil.doPost(prefix + "/findPay/createOrder.pay", paremeter);

			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder;

			CreateOrderResult result = new CreateOrderResult();
			builder = factory.newDocumentBuilder();
			Document doc = builder.parse(new ByteArrayInputStream(xmlResult.getBytes()));

			result.setOrderId(getValue(doc, "OrderId"));
			result.setRcd(getValue(doc, "Rcd"));
			result.setRdesc(getValue(doc, "RDesc"));
			result.setSign(getValue(doc, "Sign"));

			return result;
		} catch (Exception e) {
			LOG.error("创建富友支付订单出错", e);
			AssertUtil.assertFail("FUIOU_CREATE_ORDER_ERROR");
		}

		return null;
	}

	private String getValue(Document doc, String tagName) {
		NodeList nodeList = doc.getElementsByTagName(tagName);
		if (nodeList == null || nodeList.getLength() == 0) {
			return null;
		}
		Element e = (Element) nodeList.item(0);
		return e.getTextContent();
	}

}
